package com.zst.dollars;

import com.zst.dollars.common.Consts;
import com.zst.dollars.entity.connection.ClientDisconnectAnnounceMessage;
import com.zst.dollars.entity.keepalive.KeepAliveRequestMessage;
import com.zst.dollars.handler.codec.FrameCodec;
import com.zst.dollars.handler.codec.decoder.ByteToMessageDecoder;
import com.zst.dollars.handler.codec.decoder.FrameDecoder;
import com.zst.dollars.handler.codec.encoder.FrameEncoder;
import com.zst.dollars.handler.codec.encoder.MessageToByteEncoder;
import com.zst.dollars.handler.server.ClientConnectionHandler;
import com.zst.dollars.handler.server.ClientKeepAliveResponseHandler;
import com.zst.dollars.handler.server.ClientMsgRequestHandler;
import com.zst.dollars.handler.server.ClientSignInHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

public class ServerApp {
    private static final Logger logger = LoggerFactory.getLogger(ServerApp.class);

    public static void main(String[] args) throws InterruptedException {
        final ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
        final ConcurrentHashMap<String, String> clientTokenUsernameMap = new ConcurrentHashMap<>();
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                //设置客户端Channel使用到的ChannelHandler
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new FrameDecoder())
                                .addLast(new FrameEncoder())
                                .addLast(new ByteToMessageDecoder())
                                .addLast(new MessageToByteEncoder())
                                .addLast(new ClientConnectionHandler(clientTokenUsernameMap, channelGroup))
                                .addLast(new ClientKeepAliveResponseHandler())
                                .addLast(new ClientSignInHandler(clientTokenUsernameMap, channelGroup))
                                .addLast(new ClientMsgRequestHandler(clientTokenUsernameMap, channelGroup));

                    }
                })
                //添加发送心跳包的定时任务,改天建一个Handler移到里面去
                .handler(new ChannelInitializer<NioServerSocketChannel>() {
                    @Override
                    protected void initChannel(NioServerSocketChannel ch) throws Exception {
                        ch.eventLoop().scheduleAtFixedRate(() -> {
                            logger.debug("Heeloo");
                            KeepAliveRequestMessage keepAliveRequestMessage = new KeepAliveRequestMessage();
                            channelGroup.stream().forEach(channel -> {
                                int keepAliveSendCount = channel.attr(Consts.keepAliveCount).get().incrementAndGet();
                                if(keepAliveSendCount > Consts.keepALiveMaxCount){
                                    channel.close();
                                    String username = clientTokenUsernameMap.get(channel.attr(Consts.tokenKey));
                                    clientTokenUsernameMap.remove(channel.attr(Consts.tokenKey));
                                    channelGroup.remove(channel);

                                    ClientDisconnectAnnounceMessage disconnectAnnounceMessage = new ClientDisconnectAnnounceMessage(username);
                                    channelGroup.writeAndFlush(disconnectAnnounceMessage);
                                }

                                logger.debug("KeepALive Request Send");
                                channel.writeAndFlush(keepAliveRequestMessage);
                            });

                        }, 5, 30, TimeUnit.SECONDS);
                    }
                });

                ChannelFuture future = serverBootstrap.bind(Consts.port).sync();

                future.channel().closeFuture().sync();

                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();

    }
}
